package com.dingchw.singlemusic.define.response;

import com.dingchw.singlemusic.BootstrapApplication;
import com.dingchw.singlemusic.define.annotation.UnWrapper;
import com.dingchw.singlemusic.define.exception.AbstractBusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;

@RestControllerAdvice(basePackageClasses = {BootstrapApplication.class})
public class ResponseWrapper implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Class originClass = methodParameter.getMethod().getDeclaringClass();
        Annotation anno = originClass.getAnnotation(UnWrapper.class);
        UnWrapper unWrapper = methodParameter.getMethod().getAnnotation(UnWrapper.class);
        if(null != anno || null != unWrapper || (o instanceof ResponseData)){
            return o;
        }
        return new ResponseData(o);
    }

    @ExceptionHandler(value= AbstractBusinessException.class)
    public Object exceptionHandler(Throwable exp){
        if(exp instanceof AbstractBusinessException){
            AbstractBusinessException e = (AbstractBusinessException)exp;
            return new ResponseData(e.getResponseStatus(), e.getMessage());
        }else{
            return new ResponseData(ResponseStatusEnum.FAIL);
        }
    }
}
